package com.maple.hibernate;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

/**
 *  不需要打开和关闭事务
 */
public class HibernateUtil1 {

//	public static SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory() ;
	public static SessionFactory sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory() ;
	public static Map<Thread, Session> sessionMap=new HashMap<Thread, Session>(); 

	public  static Session openSession()
	{
		Session session=sessionFactory.openSession();
		sessionMap.put(Thread.currentThread(), session);
		session.beginTransaction();
		return session;
	}
	
	public  static Session getCurrentSession()
	{
		return sessionMap.get(Thread.currentThread());
	}
	
	public static void closeAndRemoveCurrentSession()
	{
		
		Session session=sessionMap.get(Thread.currentThread());
		session.getTransaction().commit();
		session.close();
		sessionMap.remove(Thread.currentThread());
	}

	
	
//	buildSessionFactory() {
//		try {
//			// Create the SessionFactory from hibernate.cfg.xml
//			return new Configuration().configure().buildSessionFactory();
//		} catch (Throwable ex) {
//			// Make sure you log the exception, as it might be swallowed
//			System.err.println("Initial SessionFactory creation failed." + ex);
//			throw new ExceptionInInitializerError(ex);
//		}
//	}

//	public static SessionFactory getSessionFactory() {
//		return sessionFactory;
//	}

}
